package com.jorenwu.asymmetric;

import java.math.BigInteger;
import java.util.Random;

public class FermatPrimeTest implements PrimeTest
{
	BigInteger num;
	int round;

	public boolean primeTest(BigInteger num, int round)
	{
		this.num = num;
		this.round = round;
		return fermatTest();
	}

	private boolean fermatTest()
	{
		for (int i = 0; i < round; i++)
		{
			Random rand = new Random(System.currentTimeMillis());
			BigInteger bignum = new BigInteger(512, rand);
			bignum = (bignum.mod(num)).subtract(BigInteger.ONE);
			if (bignum.compareTo(BigInteger.ZERO) == 0)
				bignum.add(BaseCalculator.TWO);
			if (bignum.compareTo(BigInteger.ONE) == 0)
				bignum.add(BigInteger.ONE);
			if ((bignum.gcd(num)).compareTo(BigInteger.ONE) != 0)
				return false;
			if ((bignum.modPow(num.subtract(BigInteger.ONE), num))
					.compareTo(BigInteger.ONE) != 0)
				return false;
			else
				return true;
		}
		return false;
	}

}
